package com.xindaoapp.happypet.ui;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.MainDatas;
import com.xindaoapp.happypet.bean.MainDatas.MainData;
import com.xindaoapp.happypet.protocol.MoccaApiImpl;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.RoundImageView;

/**
 * 打榜
 * 
 * @author Yomine
 */
public class ListActivity extends BaseActivity {

    private PullToRefreshListView vListView;

    private View vFoot, vHeader;

    private static int total = 0;

    private static int page = 1;
    /**
     * 下拉的状态 -1为第一次加载 0为加载 1为刷新
     */


    private boolean isFirst = true;

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_list;
    }

    @Override
    protected void initViews() {
        vListView = (PullToRefreshListView) findViewById(R.id.vList);
        // setTopCenterImage(R.drawable.bang_toppic);
        setTopBarTitle("打榜");
        super.initViews();
    }


    @SuppressWarnings("unchecked")
    @Override
    protected void initEvents() {
        vListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                // TODO Auto-generated method stub
                page = 1;
                getBangData(page, Constants.PAGE_SIZE);
            }
        });

        super.initEvents();
    }

    @Override
    protected void onLoadDatas() {
        getBangData(page, Constants.PAGE_SIZE);
        super.onLoadDatas();
    }

    private void getBangData(int pageN, final int pagesizeN) {
        if (CommonUtil.checkNetState(ListActivity.this)) {
            new MoccaApiImpl().getBangDatas(String.valueOf(pageN), String.valueOf(pagesizeN),
                    new IRequest<MainDatas>() {
                        @Override
                        public void request(MainDatas t) {
                            vListView.onRefreshComplete();
                            if (t == null) {
                                if (isFirst) {
                                    onDataArrived(false);
                                }
                            } else {
                                onDataArrived(true);
                                if (t.getResult().equals("0")) {
                                    isFirst = false;
                                    total = Integer.valueOf(t.getTotal());
                                    if (null != t.array && t.array.size() > 0) {
                                        vListView.setAdapter(new BangAdapter(
                                                getApplicationContext(), t.array,
                                                Constants.PAGE_SIZE, R.layout.bang_list_item,
                                                R.layout.item_loading));
                                    }
                                } else {
                                    if (!TextUtils.isEmpty(t.getMsg())) {
                                        Toast.makeText(ListActivity.this, t.getMsg(),
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        }
                    });
        } else {
            vListView.onRefreshComplete();
            Toast.makeText(getApplicationContext(), R.string.pLease_check_network,
                    Toast.LENGTH_SHORT).show();
        }
    }

    private class BangAdapter extends XinDaoBaseAdapter<MainData> {

        public BangAdapter(Context context, List<MainData> iniData, int pageSize, int res,
                int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent, final MainData value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();;
            if (holder == null) {
                holder = new ViewHolder();
                holder.content = (TextView) convertView.findViewById(R.id.content);
                holder.pic = (RoundImageView) convertView.findViewById(R.id.pic);
                holder.userface = (CircleImageView) convertView.findViewById(R.id.userface);
                holder.username = (TextView) convertView.findViewById(R.id.username);
                holder.views = (TextView) convertView.findViewById(R.id.views);
                holder.info = (TextView) convertView.findViewById(R.id.info);
                holder.flag = (ImageView) convertView.findViewById(R.id.flag);
                convertView.setTag(holder);
            }
            if (!TextUtils.isEmpty(value.subject)) {
                holder.content.setText(value.subject);
            }

            holder.pic
                    .setLayoutParams(new RelativeLayout.LayoutParams(
                            CommonParameter.sScreenWidth - CommonUtil.dip2px(mContext, 14),
                            (int) ((float) com.xindaoapp.happypet.utils.CommonParameter.sScreenWidth / 612 * 320)));
            ImageLoader.getInstance().displayImage(value.coverpath, holder.pic);
            ImageLoader.getInstance().displayImage(value.userface, holder.userface);
            holder.username.setText(value.author);
            holder.views.setText(value.views + "访问");
            holder.info.setText(value.replies + "参与");


            if (position == 0) {
                holder.flag.setVisibility(View.VISIBLE);
                holder.flag.setImageResource(R.drawable.bang_flag);
            } else if (position == 1) {
                holder.flag.setVisibility(View.VISIBLE);
                holder.flag.setImageResource(R.drawable.bang2);
            } else if (position == 2) {
                holder.flag.setVisibility(View.VISIBLE);
                holder.flag.setImageResource(R.drawable.bang3);
            } else {
                holder.flag.setVisibility(View.GONE);
            }
            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, value.tid);
                    intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                }
            });
            return convertView;
        }

        @Override
        public void nextPage(
                int start,
                int size,
                final com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData<MainData> iLoadNextPageData) {
            HappyPetApplication
                    .get()
                    .getMoccaApi()
                    .getBangDatas(String.valueOf(start), String.valueOf(size),
                            new IRequest<MainDatas>() {
                                @Override
                                public void request(MainDatas t) {
                                    if (null != t && t.array != null) {
                                        iLoadNextPageData.loadNextPageData(t.array);
                                    }
                                }
                            });
        }
    }
    private class ViewHolder {
        RoundImageView pic;
        TextView content;
        CircleImageView userface;
        TextView username;
        TextView views;
        TextView info;
        ImageView flag;
    }



    @Override
    protected int getTopBarLeftImageViewRes() {
        // TODO Auto-generated method stub
        return R.drawable.top_bar_back;
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        // TODO Auto-generated method stub
        return new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        };
    }

    @Override
    protected int getTopBarRightTextViewRes() {
        return R.string.shangbang;
    }

    // @Override
    // protected int getTopBarRightTextViewRes() {
    // // TODO Auto-generated method stub
    // return R.string.shangbang;
    // }



    @Override
    protected OnClickListener getRightViewClickListener() {
        // TODO Auto-generated method stub
        return new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ListActivity.this, GuiZeActivity.class);
                intent.putExtra(Constants.GUIZE, "bang");
                startActivity(intent);
            }
        };
    }
}
